package com.uzai.console.service.pyq.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.dto.pyq.PyqFollowTaskCacheDto;
import com.uzai.common.enums.MessageFuncEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.pyq.pyqfollowconfig.PyqFollowConfigDto;
import com.uzai.console.dto.pyq.pyqfollowconfig.PyqFollowConfigIdDto;
import com.uzai.console.dto.pyq.pyqfollowconfig.PyqFollowConfigQuery;
import com.uzai.console.dto.pyq.pyqfollowconfig.PyqFollowConfigStatusDto;
import com.uzai.console.dto.rocketmq.pyqfollow.FollowConfigDto;
import com.uzai.console.entity.DeviceWechatInfo;
import com.uzai.console.entity.PyqDevicePlan;
import com.uzai.console.entity.PyqFollowConfig;
import com.uzai.console.mapper.DeviceWechatInfoMapper;
import com.uzai.console.mapper.PyqDevicePlanMapper;
import com.uzai.console.mapper.PyqFollowConfigMapper;
import com.uzai.console.service.feign.UzaiImClientFeignService;
import com.uzai.console.service.pyq.PyqFollowConfigService;
import com.uzai.console.vo.pyq.pyqfollowconfig.PyqFollowConfigVo;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;

/**
 * 朋友圈跟发配置
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class PyqFollowConfigServiceImpl implements PyqFollowConfigService {

    Logger logger = LoggerFactory.getLogger(PyqFollowConfigServiceImpl.class);

    @Autowired
    private PyqFollowConfigMapper pyqFollowConfigMapper;
    @Autowired
    private UzaiImClientFeignService uzaiImClientFeignService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private PyqDevicePlanMapper pyqDevicePlanMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询朋友圈跟发配置列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqFollowConfigQuery
     * @return null
     */
    public Page<PyqFollowConfigVo> findPyqFollowConfigList(PyqFollowConfigQuery pyqFollowConfigQuery){
        //新建返回到页面的LIST对象
        List<PyqFollowConfigVo> pyqFollowConfigPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<PyqFollowConfig> page = new Page<>();
        pyqFollowConfigQuery.convert(page);
        ArrayList<PyqFollowConfig> pyqFollowConfigList =  pyqFollowConfigMapper.findByList(page, pyqFollowConfigQuery);
        if(pyqFollowConfigList != null && pyqFollowConfigList.size() > 0){
            for (PyqFollowConfig pyqFollowConfig : pyqFollowConfigList){
                PyqFollowConfigVo pyqFollowConfigPageVo = new PyqFollowConfigVo();
                BeanUtils.copyProperties(pyqFollowConfig, pyqFollowConfigPageVo);

                //设备方案名称
                if(pyqFollowConfig.getDevicePlanId() != null){
                    PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(pyqFollowConfig.getDevicePlanId(), pyqFollowConfig.getMerId());
                    if(pyqDevicePlan != null){
                        pyqFollowConfigPageVo.setDevicePlanName(pyqDevicePlan.getName());
                    }
                }

                //封装关键词过滤
                if(StringUtils.isNotBlank(pyqFollowConfig.getIgnore())){
                    List<String> ignoreList = JSONObject.parseArray(pyqFollowConfig.getIgnore(), String.class);
                    pyqFollowConfigPageVo.setIgnoreList(ignoreList);
                }

                //封装被监控微信wxid列表
                if(StringUtils.isNotBlank(pyqFollowConfig.getWxids())){
                    List<String> wxidList = JSONObject.parseArray(pyqFollowConfig.getWxids(), String.class);
                    pyqFollowConfigPageVo.setWxidList(wxidList);
                }
                pyqFollowConfigPageVoList.add(pyqFollowConfigPageVo);
            }
        }
        //返回到页面分页对象
        Page<PyqFollowConfigVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(pyqFollowConfigPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询朋友圈跟发配置详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqFollowConfigIdDto
     * @return null
     */
    public PyqFollowConfigVo findPyqFollowConfig(PyqFollowConfigIdDto pyqFollowConfigIdDto){
        if(pyqFollowConfigIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        PyqFollowConfig pyqFollowConfig = pyqFollowConfigMapper.selectById(pyqFollowConfigIdDto.getId(), pyqFollowConfigIdDto.getMerId());

        if(pyqFollowConfig == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该朋友圈跟发配置不存在");
        }

        PyqFollowConfigVo pyqFollowConfigVo = new PyqFollowConfigVo();
        BeanUtils.copyProperties(pyqFollowConfig, pyqFollowConfigVo);

        //封装关键词过滤
        if(StringUtils.isNotBlank(pyqFollowConfig.getIgnore())){
            List<String> ignoreList = JSONObject.parseArray(pyqFollowConfig.getIgnore(), String.class);
            pyqFollowConfigVo.setIgnoreList(ignoreList);
        }

        //封装被监控微信wxid列表
        if(StringUtils.isNotBlank(pyqFollowConfig.getWxids())){
            List<String> wxidList = JSONObject.parseArray(pyqFollowConfig.getWxids(), String.class);
            pyqFollowConfigVo.setWxidList(wxidList);
        }

        return pyqFollowConfigVo;
    }

    /**
     * 添加朋友圈跟发配置
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqFollowConfigDto
     * @return null
     */
    public void addPyqFollowConfig(PyqFollowConfigDto pyqFollowConfigDto){

        if(pyqFollowConfigDto.getDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }


        if(pyqFollowConfigDto.getDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(pyqFollowConfigDto.getDevicePlanId(), pyqFollowConfigDto.getMerId());
        if(pyqDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "设备方案不存在");
        }

        if(pyqFollowConfigDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择监控机器人");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(pyqFollowConfigDto.getDeviceUniqueId(), pyqFollowConfigDto.getMerId());
        if(deviceWechatInfo == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "监控机器人不存在");
        }

        if(pyqFollowConfigDto.getWxidList() == null || pyqFollowConfigDto.getWxidList().size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入被监控微信wxid");
        }

        Integer now = DateUtil.getNowTime();
        PyqFollowConfig pyqFollowConfig = new PyqFollowConfig();
        pyqFollowConfig.setId(IdWorker.getId());
        pyqFollowConfig.setName(pyqFollowConfigDto.getName());
        pyqFollowConfig.setMerId(pyqFollowConfigDto.getMerId());
        pyqFollowConfig.setDeviceUniqueId(pyqFollowConfigDto.getDeviceUniqueId());
        pyqFollowConfig.setWxids(JSONObject.toJSONString(pyqFollowConfigDto.getWxidList()));
        pyqFollowConfig.setDevicePlanId(pyqFollowConfigDto.getDevicePlanId());
        pyqFollowConfig.setStatus(0); //默认关闭
        pyqFollowConfig.setIgnore(Tools.getStrEmpty(JSONObject.toJSONString(pyqFollowConfigDto.getIgnoreList())));
        pyqFollowConfig.setImgSecret(Tools.getInteger(pyqFollowConfigDto.getImgSecret()));
        pyqFollowConfig.setEmoji(Tools.getInteger(pyqFollowConfigDto.getEmoji()));
        pyqFollowConfig.setTurnlink(Tools.getInteger(pyqFollowConfigDto.getTurnlink()));
        pyqFollowConfig.setCreateTime(now);
        pyqFollowConfig.setUpdateTime(now);
        pyqFollowConfigMapper.insert(pyqFollowConfig);
    }

    /**
     * 修改朋友圈跟发配置
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqFollowConfigDto
     * @return null
     */
    public void updatePyqFollowConfig(PyqFollowConfigDto pyqFollowConfigDto){
        if(pyqFollowConfigDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if(pyqFollowConfigDto.getDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        if(pyqFollowConfigDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择监控机器人");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(pyqFollowConfigDto.getDeviceUniqueId(), pyqFollowConfigDto.getMerId());
        if(deviceWechatInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "监控机器人不存在");
        }

        List<String> wxidList = pyqFollowConfigDto.getWxidList();
        if(wxidList == null || wxidList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入被监控微信wxid");
        }

        PyqFollowConfig pyqFollowConfig = pyqFollowConfigMapper.selectById(pyqFollowConfigDto.getId(), pyqFollowConfigDto.getMerId());
        if(pyqFollowConfig == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该跟发配置不存在");
        }

        //是否发送修改跟发配置标志
        boolean sendFollowConfigFlag = false;

        pyqFollowConfig.setMerId(pyqFollowConfigDto.getMerId());
        pyqFollowConfig.setName(pyqFollowConfigDto.getName());

        if(pyqFollowConfigDto.getDeviceUniqueId().longValue() != pyqFollowConfig.getDeviceUniqueId().longValue()){
            pyqFollowConfig.setDeviceUniqueId(pyqFollowConfigDto.getDeviceUniqueId());
            sendFollowConfigFlag = true;
        }

        String wxids = Tools.getStr(JSONObject.toJSONString(pyqFollowConfigDto.getWxidList()));
        if(!wxids.equals(pyqFollowConfig.getWxids())){
            pyqFollowConfig.setWxids(JSONObject.toJSONString(pyqFollowConfigDto.getWxidList()));
            sendFollowConfigFlag = true;
        }

        pyqFollowConfig.setDevicePlanId(pyqFollowConfigDto.getDevicePlanId());
        pyqFollowConfig.setIgnore(Tools.getStrEmpty(JSONObject.toJSONString(pyqFollowConfigDto.getIgnoreList())));
        pyqFollowConfig.setImgSecret(Tools.getInteger(pyqFollowConfigDto.getImgSecret()));
        pyqFollowConfig.setEmoji(Tools.getInteger(pyqFollowConfigDto.getEmoji()));
        pyqFollowConfig.setTurnlink(Tools.getInteger(pyqFollowConfigDto.getTurnlink()));
        Integer now = DateUtil.getNowTime();
        pyqFollowConfig.setUpdateTime(now);
        pyqFollowConfigMapper.updateById(pyqFollowConfig);

        //判断是否修改了监听机器人或者被监控微信wxid
        if(sendFollowConfigFlag){
            try {
                //发送微服务，通知终端
                MsgDto<FollowConfigDto> msgDto = new MsgDto<>();
                FollowConfigDto followConfigDto = new FollowConfigDto();
                msgDto.setContent(followConfigDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
                msgDto.setMerId(deviceWechatInfo.getMerId());
                msgDto.setMsgType(MessageFuncEnum.MONITOR_SNSNEW_TASK.getValue());
                //封装参数对象
                followConfigDto.setId(pyqFollowConfig.getId());
                followConfigDto.setDeviceId(deviceWechatInfo.getDeviceId());
                followConfigDto.setOprState(Tools.getInteger(pyqFollowConfig.getStatus()));
                followConfigDto.setArrWxids(StringUtils.join(wxidList,";"));
                UzaiRespVo<Boolean> uzaiRespVo =  uzaiImClientFeignService.pyqFollow(msgDto);

                logger.info("---调用朋友圈跟发配置同步功能接口----para={},result={}", JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));

                //更新缓存-用于移动端
                if(Tools.getInteger(pyqFollowConfig.getStatus()).intValue() == 0){ //关闭，删除
                    redisTemplate.opsForHash().delete(RedisCacheKeyEnum.CIRCLE_FOLLOW_TASK_CACHE_KEY.getKey(), pyqFollowConfigDto.getId());
                }else{//开启-增加
                    PyqFollowTaskCacheDto pyqFollowTaskCacheDto = new PyqFollowTaskCacheDto();
                    pyqFollowTaskCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
                    pyqFollowTaskCacheDto.setDeviceId(deviceWechatInfo.getDeviceId());
                    pyqFollowTaskCacheDto.setWxIds(wxidList);
                    redisTemplate.opsForHash().put(RedisCacheKeyEnum.CIRCLE_FOLLOW_TASK_CACHE_KEY.getKey(), pyqFollowConfigDto.getId(), JSONObject.toJSONString(pyqFollowTaskCacheDto));
                }
            }catch(Exception e) {}
        }
    }

    /**
     * 删除
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqFollowConfigIdDto
     * @return null
     */
    public void deletePyqFollowConfig(PyqFollowConfigIdDto pyqFollowConfigIdDto){
        if(pyqFollowConfigIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        PyqFollowConfig pyqFollowConfig = pyqFollowConfigMapper.selectById(pyqFollowConfigIdDto.getId(), pyqFollowConfigIdDto.getMerId());

        if(pyqFollowConfig == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此跟发配置不存在");
        }
        //删除
        pyqFollowConfigMapper.deleteById(pyqFollowConfigIdDto.getId(), pyqFollowConfigIdDto.getMerId());

        if(pyqFollowConfig.getDeviceUniqueId() != null){
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(pyqFollowConfig.getDeviceUniqueId(), pyqFollowConfig.getMerId());
            if(deviceWechatInfo != null){
                List<String> wxidList = null;
                String wxids = Tools.getStr(pyqFollowConfig.getWxids());
                if(StringUtils.isNotBlank(wxids)){
                    wxidList = JSONObject.parseArray(wxids, String.class);
                }
                if(wxidList == null){
                    wxidList = new ArrayList<>();
                }
                try {
                    //发送微服务，通知终端
                    MsgDto<FollowConfigDto> msgDto = new MsgDto<>();
                    FollowConfigDto followConfigDto = new FollowConfigDto();
                    msgDto.setContent(followConfigDto);
                    msgDto.setId(IdWorker.getId());
                    msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                    msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
                    msgDto.setMerId(deviceWechatInfo.getMerId());
                    msgDto.setMsgType(MessageFuncEnum.MONITOR_SNSNEW_TASK.getValue());
                    //封装参数对象
                    followConfigDto.setId(pyqFollowConfig.getId());
                    followConfigDto.setDeviceId(deviceWechatInfo.getDeviceId());
                    followConfigDto.setOprState(2); //删除
                    followConfigDto.setArrWxids(StringUtils.join(wxidList,";"));
                    UzaiRespVo<Boolean> uzaiRespVo =  uzaiImClientFeignService.pyqFollow(msgDto);

                    logger.info("---调用朋友圈跟发配置同步功能接口----para={},result={}", JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));

                    //更新缓存-用于移动端
                    redisTemplate.opsForHash().delete(RedisCacheKeyEnum.CIRCLE_FOLLOW_TASK_CACHE_KEY.getKey(), pyqFollowConfigIdDto.getId());

                }catch(Exception e) {}
            }
        }
    }

    /**
     * 设置是否开启
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqFollowConfigStatusDto
     * @return null
     */
    public void updateStatus(PyqFollowConfigStatusDto pyqFollowConfigStatusDto){
        if(pyqFollowConfigStatusDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        PyqFollowConfig pyqFollowConfig = pyqFollowConfigMapper.selectById(pyqFollowConfigStatusDto.getId(), pyqFollowConfigStatusDto.getMerId());

        if(pyqFollowConfig == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此跟发配置不存在");
        }

        if(pyqFollowConfig.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "监控机器人唯一id不能为空");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(pyqFollowConfig.getDeviceUniqueId(), pyqFollowConfig.getMerId());
        if(deviceWechatInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "监控机器人不存在");
        }

        String wxids = Tools.getStr(pyqFollowConfig.getWxids());
        if(StringUtils.isBlank(wxids)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "被监控微信wxid不能为空");
        }

        List<String> wxidList = JSONObject.parseArray(wxids, String.class);

        if(wxidList == null || wxidList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "被监控微信wxid不能为空");
        }

        pyqFollowConfig.setStatus(Tools.getInteger(pyqFollowConfigStatusDto.getStatus()));

        //修改状态
        pyqFollowConfigMapper.updateStatusById(pyqFollowConfig);

        try {
            //发送微服务，通知终端
            MsgDto<FollowConfigDto> msgDto = new MsgDto<>();
            FollowConfigDto followConfigDto = new FollowConfigDto();
            msgDto.setContent(followConfigDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
            msgDto.setMerId(deviceWechatInfo.getMerId());
            msgDto.setMsgType(MessageFuncEnum.MONITOR_SNSNEW_TASK.getValue());
            //封装参数对象
            followConfigDto.setId(pyqFollowConfig.getId());
            followConfigDto.setDeviceId(deviceWechatInfo.getDeviceId());
            followConfigDto.setOprState(Tools.getInteger(pyqFollowConfigStatusDto.getStatus()));
            followConfigDto.setArrWxids(StringUtils.join(wxidList,";"));
            UzaiRespVo<Boolean> uzaiRespVo =  uzaiImClientFeignService.pyqFollow(msgDto);

            logger.info("---调用朋友圈跟发配置同步功能接口----para={},result={}", JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));

            //更新缓存-用于移动端
            if(Tools.getInteger(pyqFollowConfigStatusDto.getStatus()).intValue() == 0){ //关闭，删除
                redisTemplate.opsForHash().delete(RedisCacheKeyEnum.CIRCLE_FOLLOW_TASK_CACHE_KEY.getKey(), pyqFollowConfigStatusDto.getId());
            }else{//开启-增加
                PyqFollowTaskCacheDto pyqFollowTaskCacheDto = new PyqFollowTaskCacheDto();
                pyqFollowTaskCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
                pyqFollowTaskCacheDto.setDeviceId(deviceWechatInfo.getDeviceId());
                pyqFollowTaskCacheDto.setWxIds(wxidList);
                redisTemplate.opsForHash().put(RedisCacheKeyEnum.CIRCLE_FOLLOW_TASK_CACHE_KEY.getKey(), pyqFollowConfigStatusDto.getId(), JSONObject.toJSONString(pyqFollowTaskCacheDto));
            }
        }catch(Exception e) {}
    }

}
